package com.liguang.rcs.admin.service;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.liguang.rcs.admin.db.entity.DodmsUserEntity;
import com.liguang.rcs.admin.db.repository.DodmsUserRepository;
import com.liguang.rcs.admin.util.response.PageableBody;
import com.liguang.rcs.admin.web.user.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
public class DodmsUserService {

    @Autowired
    private DodmsUserRepository repository;

    public List<DodmsUserEntity> findUser(String username) {
        return repository.findByUserName(username);
    }

    public PageableBody<UserVO> querySelective(String username, Integer page, Integer limit, String sort, String order) {

        Pageable pageable = PageRequest.of(page - 1, limit, Sort.Direction.fromString(order), sort);

        Page<DodmsUserEntity> userPage = repository.findAll((Specification<DodmsUserEntity>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> conditionLst = Lists.newArrayList();
            conditionLst.add(criteriaBuilder.equal(root.get("deleted"), false));
            if (!Strings.isNullOrEmpty(username)) {
                conditionLst.add(criteriaBuilder.like(root.get("userName"), "%" + username + "%"));
            }
            return criteriaBuilder.and(conditionLst.toArray(new Predicate[conditionLst.size()]));
        }, pageable);
        return PageableBody.buildFrom(userPage, UserVO::buildFrom);
    }

    public void add(DodmsUserEntity entity) {
        repository.save(entity);
    }

    public DodmsUserEntity findById(Long id) {
        Optional<DodmsUserEntity> entity = repository.findById(id);
        return entity.isPresent() ? entity.get() : null;
    }

    public void updateById(DodmsUserEntity user) {
         repository.save(user);
    }

    @Transactional
    public void deleteById(Long id) {
        DodmsUserEntity entity = findById(id);
        if (entity != null) {
            entity.setDeleted(true);
            repository.save(entity);
        }
    }

    public List<DodmsUserEntity> all() {
        return repository.findByDeleted(false);
    }
}
